/* MQTT (over TCP) Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "esp_wifi.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "protocol_examples_common.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.h"
#include "freertos/timers.h"

#include "lwip/sockets.h"
#include "lwip/dns.h"
#include "lwip/netdb.h"

#include "esp_log.h"
#include "mqtt_client.h"

#include "bsp_uart.h"
#include "app_main.h"

/* 不同设备修改这些 */

//char* MQTT_CLIENT_ID = "GID_qsbao_test@@@device_test_2";
//char* MQTT_USERNAME = "Signature|LTAI5tJzaFmSDecnAf6astcQ|post-cn-0gx3se5kd02";
//char* MQTT_PASSWORD = "emb5dczoN55XrYG7P4Spxyv0N/4=";
//#define CLIENT_ID  "V20483BE-V204D21A"

//char* MQTT_CLIENT_ID = "GID_qsbao_test@@@V2045AE5-V204D177";
//char* MQTT_USERNAME = "Signature|LTAI5tJzaFmSDecnAf6astcQ|post-cn-0gx3se5kd02";
//char* MQTT_PASSWORD = "TpvaKxvpYPYs4KMgkFpTSlKmbl4=";
//#define CLIENT_ID  "V2045AE5-V204D177"

char* MQTT_CLIENT_ID = "GID_qsbao_test@@@V204FA08-V2044313";
char* MQTT_USERNAME = "Signature|LTAI5tJzaFmSDecnAf6astcQ|post-cn-0gx3se5kd02";
char* MQTT_PASSWORD = "ilvZmG029d/zOspTKMcaJGV7zSA=";
#define CLIENT_ID  "V204FA08-V2044313"

char * SUBSCRIBE_CMD = "shoes/"CLIENT_ID"/command/sub";
char * PUBLISH_CMD   = "shoes/"CLIENT_ID"/command/pub";
char * PUBLISHE_SYNC_DATA = "shoes/"CLIENT_ID"/sync_data";
char * PUBLISHE_REALTIME_DATA = "shoes/"CLIENT_ID"/realtime_data";

void led_on(void);
void led_off(void);

static const char *TAG = "MQTT_EXAMPLE";

//static void log_error_if_nonzero(const char *message, int error_code)
//{
//    if (error_code != 0) {
//        ESP_LOGE(TAG, "Last error %s: 0x%x", message, error_code);
//    }
//}

static esp_mqtt_client_handle_t m_aliyun_client;

static char* test_msg = "hello_world";

int esp_mqtt_pulish_msg(const char* topic, char* buf, int len)
{
	esp_mqtt_client_publish(m_aliyun_client, topic, buf, len, 0, 1);
	return 0;
}
/*
 * @brief Event handler registered to receive MQTT events
 *
 *  This function is called by the MQTT client event loop.
 *
 * @param handler_args user data registered to the event.
 * @param base Event base for the handler(always MQTT Base in this example).
 * @param event_id The id for the received event.
 * @param event_data The data for the event, esp_mqtt_event_handle_t.
 */
static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data)
{
    ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%" PRIi32 "", base, event_id);
    esp_mqtt_event_handle_t event = event_data;
    esp_mqtt_client_handle_t client = event->client;
    int msg_id;
    switch ((esp_mqtt_event_id_t)event_id) {
    case MQTT_EVENT_CONNECTED:
        ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
    	led_on();

        msg_id = esp_mqtt_client_subscribe(client, SUBSCRIBE_CMD, 0);
        ESP_LOGI(TAG, "msg_id=%d",msg_id);

        break;
    case MQTT_EVENT_DISCONNECTED:
        ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
        led_off();
        break;

    case MQTT_EVENT_SUBSCRIBED:
        ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_UNSUBSCRIBED:
        ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_PUBLISHED:
        ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_DATA:
        //ESP_LOGI(TAG, "MQTT_EVENT_DATA");
        //printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
        //printf("DATA=%.*s\r\n", event->data_len, event->data);

    	/* 将MQTT接收数据解析发送--->UART */
    	usr_mqtt_recv_msg((uint8_t*)event->data, event->data_len);
        break;
    case MQTT_EVENT_ERROR:
        ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
        break;
    default:
        ESP_LOGI(TAG, "Other event id:%d", event->event_id);
        break;
    }
}

static void mqtt_app_start(void)
{
    esp_mqtt_client_config_t mqtt_cfg = {
    	.broker.address.transport = MQTT_TRANSPORT_OVER_TCP,
        .broker.address.hostname = "post-cn-0gx3se5kd02.mqtt.aliyuncs.com",
		.broker.address.port = 1883,
		.credentials.client_id = MQTT_CLIENT_ID,
		.credentials.username = MQTT_USERNAME,
		.credentials.authentication.password = MQTT_PASSWORD,
    };

#if CONFIG_BROKER_URL_FROM_STDIN
    char line[128];

    if (strcmp(mqtt_cfg.broker.address.uri, "FROM_STDIN") == 0) {
        int count = 0;
        printf("Please enter url of mqtt broker\n");
        while (count < 128) {
            int c = fgetc(stdin);
            if (c == '\n') {
                line[count] = '\0';
                break;
            } else if (c > 0 && c < 127) {
                line[count] = c;
                ++count;
            }
            vTaskDelay(10 / portTICK_PERIOD_MS);
        }
        mqtt_cfg.broker.address.uri = line;
        printf("Broker url: %s\n", line);
    } else {
        ESP_LOGE(TAG, "Configuration mismatch: wrong broker url");
        abort();
    }
#endif /* CONFIG_BROKER_URL_FROM_STDIN */

    esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
    /* The last argument may be used to pass data to the event handler, in this example mqtt_event_handler */
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
    esp_mqtt_client_start(client);
    m_aliyun_client = client;
}

static TimerHandle_t Timer1_Handle =NULL;
static uint32_t TmrCb_Count1 = 0;

static void Swtmr1_Callback(void* parameter)
{
	TmrCb_Count1++;
	if(TmrCb_Count1%10==0)
	{
		esp_mqtt_pulish_msg(SUBSCRIBE_CMD, test_msg, strlen(test_msg));
		esp_mqtt_pulish_msg(PUBLISHE_SYNC_DATA, test_msg, strlen(test_msg));
		esp_mqtt_pulish_msg(PUBLISHE_REALTIME_DATA, test_msg, strlen(test_msg));
	}
}

void start_timer_sys(void)
{
	Timer1_Handle=xTimerCreate((const char*)"AutoReloadTimer",
	                          (TickType_t)(100/portTICK_PERIOD_MS),/* 定时器周期 1000(tick) */
	                          (UBaseType_t)pdTRUE,/* 周期模式 */
	                          (void*)1,/* 为每个计时器分配一个索引的唯一ID */
	                          (TimerCallbackFunction_t)Swtmr1_Callback);
	if(Timer1_Handle != NULL)
	{
		xTimerStart(Timer1_Handle,0);
	}
}

//static uint8_t s_led_state = 1;

void led_on(void)
{
    /* Set the GPIO level according to the state (LOW or HIGH)*/
    gpio_set_level(BLINK_GPIO, 1);
}
void led_off(void)
{
    /* Set the GPIO level according to the state (LOW or HIGH)*/
    gpio_set_level(BLINK_GPIO, 0);
}
void configure_led(void)
{
    gpio_reset_pin(BLINK_GPIO);
    /* Set the GPIO as a push/pull output */
    gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT);
}

void app_main(void)
{
    ESP_LOGI(TAG, "[APP] Startup..");
    ESP_LOGI(TAG, "[APP] Free memory: %" PRIu32 " bytes", esp_get_free_heap_size());
    ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());

    esp_log_level_set("*", ESP_LOG_INFO);
    esp_log_level_set("mqtt_client", ESP_LOG_VERBOSE);
    esp_log_level_set("MQTT_EXAMPLE", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT_BASE", ESP_LOG_VERBOSE);
    esp_log_level_set("esp-tls", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
    esp_log_level_set("outbox", ESP_LOG_VERBOSE);

    ESP_ERROR_CHECK(nvs_flash_init());
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    configure_led();
    led_off();

    /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
     * Read "Establishing Wi-Fi or Ethernet Connection" section in
     * examples/protocols/README.md for more information about this function.
     */
    ESP_ERROR_CHECK(example_connect());
    mqtt_app_start();

    vTaskDelay(2000 / portTICK_PERIOD_MS);

    start_task_sys();
	bsp_uart1_init();
	bsp_uart2_init();
    start_task_uart();
}
